<template>
  <div class="bool-main" :style="bool_main_style">
    <!-- query fields -->
    <template
      v-if="
        queryConditionTree.children && queryConditionTree.children.length > 0
      "
    >
      <div
        class="filter-item"
        v-for="(item, index) in queryConditionTree.children"
        :key="index"
      >
        <QueryTag
          v-if="item.fieldId"
          :allFields="allFields"
          :queryCondition="item"
          @close="removeCondition"
        >
        </QueryTag>

        <!-- bool query recursion -->
        <div v-if="item.boolType">
          <bool-query
            :allFields="allFields"
            :level="level ? level + 1 : 0"
            :queryConditionTree="item"
            @addCondition="handleChildAddCondition"
            @delCondition="handleChildRemoveCondition"
          >
          </bool-query>
        </div>
      </div>
    </template>

    <!-- add filter btn -->
    <div class="add-filter">
      <span ref="addFilterRef" @click="openDialog" class="link-button">
        + Add filter
      </span>
      <span v-show="false">嵌套层级({{ level }})</span>
    </div>

    <!-- bool option -->
    <div style="width:100px">
      <el-select
        size="mini"
        v-model="selectedBoolType"
        @change="selectedBoolTypeChanged"
      >
        <el-option
          v-for="item in boolTypes"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
    </div>

    <el-dialog
      :visible="dialogVisible"
      title="Add filter"
      width="50%"
      center
      :modal="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <div v-show="currentStep === 1" class="child-query-type">
          <el-radio label="bool" v-model="childQueryType">bool 查询</el-radio>
          <el-radio label="field" v-model="childQueryType"> 普通字段</el-radio>
        </div>
        <div v-show="currentStep === 2" class="filter-form">
          <el-form ref="filterFormRef" v-model="formData" size="small">
            <div class="nl-form-row">
              <el-form-item
                label="bool type"
                v-show="childQueryType === 'bool'"
              >
                <el-radio-group v-model="formData.childBoolType">
                  <el-radio
                    v-for="item in boolTypes"
                    :key="item.id"
                    :label="item.id"
                    >{{ item.name }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </div>
            <div class="nl-form-row">
              <div>
                <el-form-item label="Field" prop="field">
                  <el-select
                    v-model="formData.field"
                    placeholder="请选择"
                    @change="selectedFieldChanged"
                  >
                    <el-option
                      v-for="item in allFields"
                      :key="item.id"
                      :label="item.fieldEnName"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>

              <div>
                <el-form-item label="Operator" prop="operator">
                  <el-select v-model="formData.operator" placeholder="请选择">
                    <el-option
                      v-for="item in queryTypes"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>

            <!-- 字符串值 -->
            <div v-if="showOperatorMethod === 'Input'" class="nl-form-row">
              <el-form-item label="Value" prop="inputValue">
                <el-input
                  v-model="formData.inputValue"
                  placeholder="Please input"
                ></el-input>
              </el-form-item>
            </div>

            <!-- 日期范围 -->
            <div
              v-else-if="showOperatorMethod === 'DateRange'"
              class="nl-form-row"
            >
              <div>
                <el-form-item label=" Min Value" prop="rangeStart">
                  <el-date-picker
                    v-model="formData.rangeStart"
                    type="date"
                    placeholder="Pick a day"
                  />
                </el-form-item>
              </div>

              <div>
                <el-form-item label="Max Value" prop="rangeEnd">
                  <el-date-picker
                    v-model="formData.rangeEnd"
                    type="date"
                    placeholder="Pick a day"
                  />
                </el-form-item>
              </div>
            </div>

            <!-- 数字范围 -->
            <div
              v-else-if="showOperatorMethod === 'NumRange'"
              class="nl-form-row"
            >
              <div>
                <el-form-item label="Min Value" prop="rangeStart">
                  <el-input-number v-model="formData.rangeStart" />
                </el-form-item>
              </div>
              <div>
                <el-form-item label="Max Value" prop="rangeEnd"
                  ><el-input-number v-model="formData.rangeEnd"
                /></el-form-item>
              </div>
            </div>

            <!-- 其它范围, Input -->
            <div v-else-if="showOperatorMethod === 'StrRange'">
              <div>
                <el-form-item label="Min Value" prop="rangeStart">
                  <el-input v-model="formData.rangeStart" />
                </el-form-item>
              </div>
              <div>
                <el-form-item label="Max Value" prop="rangeEnd">
                  <el-input v-model="formData.rangeEnd" />
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
      </div>

      <div class="dialog-footer">
        <el-button v-show="currentStep === 2" @click="preStep">
          上一步
        </el-button>

        <el-button
          v-show="currentStep === 1"
          @click="nextStep"
          :disabled="!childQueryType"
        >
          下一步
        </el-button>

        <el-button v-show="currentStep === 2" @click="submit"> 确定 </el-button>

        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fieldTypes, queryTypes, queryNames, boolTypes } from '../queryDef';
import QueryTag from './queryTag.vue';

export default {
  name: 'bool-query',
  components: { QueryTag },
  props: ['allFields', 'level', 'queryConditionTree'],
  data() {
    return {
      id: '',
      parentId: '',
      selectedBoolType: '',

      fieldTypes,
      queryTypes,
      queryNames,
      boolTypes,

      selectedFieldType: '',

      // 弹框
      dialogVisible: false,
      currentStep: 1,

      childQueryType: '', // 第一步,选择操作 Bool/Field

      // 第二步, 选择条件
      formData: {
        childBoolType: '',
        field: '',
        operator: '',
        inputValue: '',
        rangeStart: '',
        rangeEnd: '',
      },

      //
      bool_main_style: {
        borderColor: '#0071c2',
      },
    };
  },
  computed: {
    showOperatorMethod() {
      const selField = this.allFields.find(x => x.id === this.formData.field);
      const selOperator = this.queryTypes.find(
        x => x.id === this.formData.operator
      );

      const rangeType = this.queryTypes.find(x => x.value === 'range');

      if (selField && selOperator && rangeType) {
        if (selOperator.id === rangeType.id) {
          // range:
          switch (selField.fieldType.toUpperCase()) {
            case fieldTypes.Date.toUpperCase():
              return 'DateRange';

            case fieldTypes.Num.toUpperCase():
              return 'NumRange';

            default:
              return 'StrRange';
          }
        } else {
          return 'Input';
        }
      } else {
        return '';
      }
    },
  },
  created() {
    this.id = this.queryConditionTree.id;
    this.parentId = this.queryConditionTree.parentId;

    this.selectedBoolType = this.queryConditionTree.boolType;
  },
  mounted() {
    this.changeBoolMainStyle(this.selectedBoolType);
  },
  methods: {
    removeCondition(item) {
      this.$emit('delCondition', item);
    },

    selectedBoolTypeChanged(val) {
      this.changeBoolMainStyle(val);
      this.$emit('alterCondition', { id: this.id, boolType: val });
    },

    changeBoolMainStyle(boolType) {
      switch (boolType) {
        case 1: // Must
          this.bool_main_style.borderColor = '#0071c2';
          break;

        case 2: // Not
          this.bool_main_style.borderColor = '#ec2126';
          break;

        case 3: // Should
          this.bool_main_style.borderColor = '#44c28a';
          break;

        default:
          this.bool_main_style.borderColor = '#ffff00';
      }
    },

    // Dialog中的操作
    openDialog() {
      this.formData.childBoolType = '';
      this.formData.field = '';
      this.formData.operator = '';

      this.formData.inputValue = '';

      this.formData.rangeStart = '';
      this.formData.rangeEnd = '';

      this.currentStep = 1;
      this.dialogVisible = true;
    },

    preStep() {
      this.currentStep = 1;
    },
    nextStep() {
      this.currentStep = 2;
    },

    selectedFieldChanged(val) {
      // const currentSelectedField = this.allFields.find(
      //   x => x.id === this.formData.field
      // );
      // if (currentSelectedField) {
      //   this.selectedFieldType = currentSelectedField.fieldType;
      //   this.availableOperators = this.operators.filter(x =>
      //     x.fieldTypes.some(y => y === currentSelectedField.fieldType)
      //   );
      // }
    },

    submit() {
      if (this.formData.field !== '') {
        // 父级
        const parentData = {
          id: this.queryConditionTree.id,
          parentId: this.queryConditionTree.parentId,
          boolType: this.selectedBoolType,
        };

        // 新增
        const type = this.childQueryType; // field/bool

        const boolType = this.formData.childBoolType; // 如果 type===filed => must should must_not

        const fieldId = this.formData.field;

        const operatorId = this.formData.operator; // IS LIKE IN RANGE

        let value = '';

        switch (this.showOperatorMethod) {
          case 'Input':
            value = this.formData.inputValue;
            break;

          case 'DateRange':
            value = {
              gte: this.formData.rangeStart,
              lte: this.formData.rangeEnd,
            };

            break;

          case 'NumRange':
            value = {
              gte: this.formData.rangeStart,
              lte: this.formData.rangeEnd,
            };

            break;

          case 'StrRange':
            value = {
              gte: this.formData.rangeStart,
              lte: this.formData.rangeEnd,
            };

            break;
        }

        const childData = {
          type,
          boolType,
          fieldId,
          operatorId,
          value,
        };

        this.$emit('addCondition', { parentData, childData });
        this.dialogVisible = false;
      }
    },

    cancel() {
      this.dialogVisible = false;
    },

    // 递归组件
    handleChildAddCondition(condition) {
      this.$emit('addCondition', condition);
    },

    handleChildRemoveCondition(item) {
      this.$emit('delCondition', item);
    },
  },
};
</script>

<style scoped>
.bool-main {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
  align-content: center;
  background-color: #fafbfd;

  border-style: solid;
  border-width: 1px;
  border-radius: 8px;
  padding: 0 8px;
}

.filter-item {
  display: flex;
  flex-wrap: wrap;
  margin: 10px;
}

.add-filter {
  margin: 0 10px;
}

.link-button {
  color: #0071c2;
}

.link-button:hover {
  cursor: pointer;
  text-decoration: underline;
}

.dialog-body {
  margin-bottom: 20px;
}

.child-query-type {
  margin: 0 20px;
}

.filter-form {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.nl-form-row {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
}

.dialog-footer {
  display: flex;
  align-content: center;
  justify-content: center;
}
</style>
